package com.bit.cfdi.web.services;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bit.cfdi.web.domain.Contacto;
import com.bit.cfdi.web.domain.DBConstants;
import com.bit.cfdi.web.domain.Direccion;
import com.bit.cfdi.web.domain.Persona;
import com.bit.cfdi.web.domain.Usuario;
import com.bit.cfdi.web.utils.EncryptionUtils;
import com.bit.cfdi.web.utils.PasswordGenerator;

@Service
public class RegisterService {
	
	private Logger log = LogManager.getLogger(this.getClass().getName());

	@Autowired private UsuarioService usuarioService;
	@Autowired private MailService mailService;
	@Autowired private EncryptionUtils encryptionUtils;
	@Autowired private PasswordGenerator passwordGenerator;
	
	public String doRegister(final String userEmail, final String userPassword) 
			throws Exception {
		
		log.info("Creating user with email: "+userEmail);
		String codigoActivacion = passwordGenerator.generatePassword(20);
		Usuario usuario = new Usuario();
		usuario.setEmail(userEmail);
		usuario.setPassword(encryptionUtils.stringEncryption(userPassword));
		usuario.setCodigoActivacion(codigoActivacion);
		usuario.setStatus(DBConstants.STATUS_INACTIVE);
		
		Persona persona = new Persona();
		usuario.setPersona(persona);
		
		Direccion direccion = new Direccion();
		persona.setDireccion(direccion);
		
		Contacto contacto = new Contacto();
		persona.setContacto(contacto);
		
		try {
			usuarioService.save(usuario);
			log.info("user: "+userEmail+ "was persisted");
		}catch(DataAccessException dae) {
			throw new Exception("Error: no se pudo guardar el usuario");
		}
		
		return codigoActivacion;
		
	}
	
	public void sendRegistrationMail(final String userEmail, 
			final String userPassword, final String codigoActivacion) 
			throws Exception {
		
		log.info("Sending email to: "+userEmail+" to complete registration");
		String from = "support@factureya.com";
		String to = userEmail;
		String subject = "Registro a factureya";
		String msg = "<html>Bienvendio a factureya<br>" +
				"Codigo de Activacion: "+codigoActivacion+"<br>" +
				"Usuario: "+userEmail+"<br>" +
				"Password: "+userPassword + "<br>" +
				"<br>" +
				"Debe ingresar el codigo de activacion en el siguiente link " +
				"para ACTIVAR su cuenta: <br>" +
				"http://localhost:8080/CFDI-WEB/activar.zul?email="+userEmail +
				"</html>";
		
		mailService.sendMail(from, to, subject, msg);
	}
}
